package com.jy.api.controller.admin;

import com.jy.api.dao.OrderDao;
import com.jy.api.dao.OrderItemDao;
import com.jy.api.dao.StoreDao;
import com.jy.api.domain.*;
import com.jy.api.service.OrderService;
import com.jy.api.service.ProductTypeService;
import com.jy.api.util.DateAndTimeUtil;
import com.jy.api.util.ISyncExecutor;
import com.jy.api.util.RedisSyncLocker;
import com.jy.api.vo.admin.AdminOrderVo;
import com.jy.api.vo.pos.order.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lihu on 2017/10/30.
 */

@Slf4j
@RestController
@RequestMapping(value = "v1/admin", produces = "application/json;charset=utf-8")
public class AdminOrderController {


    @Autowired
    OrderDao orderDao;


    @Autowired
    OrderService orderService;

    @Autowired
    StoreDao storeDao;


    @Autowired
    OrderItemDao orderItemDao;

    @Autowired
    ProductTypeService productTypeService;
    @Autowired
    private RedisSyncLocker redisSyncLocker;

    /**
     * 获取订单信息
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/orders/{orderId}")
    public ResponseEntity getOrder(@PathVariable String orderId) throws Exception {
        return (ResponseEntity) redisSyncLocker.idLock(orderId, o -> {
            Order order = orderDao.findOne(orderId);
            if (order == null) {
                return new ResponseEntity("订单不存在", HttpStatus.BAD_REQUEST);
            }
            return new ResponseEntity(orderService.orderVoCouponInstance(order), HttpStatus.OK);
        });
    }

    /**
     * 会员消费明细
     *
     * @param pageable
     * @param storeId
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(method = RequestMethod.GET, value = "/member-sales")
    public ResponseEntity getInventories(@PageableDefault(value = 10, sort = {"paymentTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                                         @RequestParam(name = "storeId") String storeId,
                                         @RequestParam(name = "memberId") String memberId) {
        return new ResponseEntity(orderDao.findListByStoreIdAndStatusAndMemberIdAndPaymentTimeAfter(storeId,
                OrderStatus.FINISHED, memberId, DateAndTimeUtil.getMonthTime(), pageable), HttpStatus.OK);
    }

    /**
     * 订单明细
     *
     * @param orderId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "{orderId}/order-info")
    public ResponseEntity getOrderInfo(@PathVariable String orderId) {
        try {
            return (ResponseEntity) redisSyncLocker.idLock(orderId, o -> {
                Order order = orderDao.findOne(orderId);
                if (order == null) {
                    return new ResponseEntity("查询失败！订单信息不存在！", HttpStatus.BAD_REQUEST);
                }
                Store store = storeDao.findOne(order.getStoreId());
                OrderVo orderVo = orderService.orderVoCouponInstance(order);
                orderVo.setStoreName(store.getName());
                orderVo.setStoreAddress(store.getAddr());
                return ResponseEntity.ok(orderVo);
            });
        } catch (Exception ex) {

            log.error("getChargeRules is error=>orderId:{}", orderId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     * 获取时间段订单信息
     *
     * @param storeId
     * @param from
     * @param to
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "{storeId}/order/list")
    public ResponseEntity getOrderList(@PathVariable String storeId,
                                       @RequestParam(name = "from") String from,
                                       @RequestParam(name = "to") String to,
                                       @RequestParam(name = "channel", defaultValue = "") PaymentChannel channel,
                                       @RequestParam(name = "source", defaultValue = "") OrderSource source,
                                       @RequestParam(name = "status", defaultValue = "") OrderStatus status,
                                       @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
                                       @RequestParam(name = "pageNumber", defaultValue = "0") int pageNumber) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            Date start = simpleDateFormat.parse(from);
            Date end = simpleDateFormat.parse(to);
            long number = orderDao.getAdminOrderVoLength(storeId, channel, source, status, start, end);
            int page = (int) Math.ceil(number / (float) pageSize);
            AdminOrderVo adminOrderVo = new AdminOrderVo(page, number);
            adminOrderVo.setOrders(orderDao.getAdminOrderVo(storeId, channel, source, status, start, end, pageNumber, pageSize));
            return ResponseEntity.ok(adminOrderVo);
        } catch (Exception ex) {
            log.error("getOrderList is error=>storeId:{},from:{},to:{}," +
                            "channel:{},source:{},status:{},pageSize:{},PageNumber:{}",
                    storeId, from, to, channel, source, status, pageSize, pageNumber, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 获取时间段内商品销售信息
     *
     * @param storeId
     * @param from
     * @param to
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "{storeId}/product-sales")
    public ResponseEntity getSalesProduct(@PathVariable String storeId,
                                          @RequestParam(name = "productTypeId", defaultValue = "") String typeId,
                                          @RequestParam(name = "productId", defaultValue = "") String productId,
                                          @RequestParam(name = "from") String from,
                                          @RequestParam(name = "to") String to) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            Date start = simpleDateFormat.parse(from);
            Date end = simpleDateFormat.parse(to);
            List<String> typeIds = new ArrayList<>();
            if (StringUtils.isNotBlank(typeId) && StringUtils.isBlank(productId)) {
                typeIds = productTypeService.getTypeIds(typeId);
            }
            List<Map<String, Object>> maps = orderItemDao.getProductTotal(storeId, typeIds, productId, start, end);
            for (Map<String, Object> map : maps) {
                map.put("amount", (Math.rint(Double.parseDouble(map.get("amount").toString()) * 100)) / 100d);
            }
            return ResponseEntity.ok(maps);
        } catch (Exception ex) {
            log.error("getOrderList is error=>storeId:{},from:{},to:{}", storeId, from, to, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);

        }

    }


}